#include <QQmlEngine>
#include <QSqlQuery>
#include <QUuid>

#include "../global/QmlNames.h"
#include "../util/Singleton.h"
#include "../persist/DbManager.h"
#include "MessagesManager.h"

X_BEGIN_NAMESPACE

const char MessagesManager::READ_MAX_MESSAGE_ID[] = "select max(id) from messages";
QAtomicInt MessagesManager::NEXT_MESSAGE_ID(0);

MessagesManager::MessagesManager(QObject *parent)
    : QObject(parent)
{
}

MessagesManager &MessagesManager::instance()
{
    return *Singleton<MessagesManager>::instance(MessagesManager::createInstance);
}

const char *MessagesManager::qmlName()
{
    return QmlNames::TopLevelModelSingleton::MessagesSingleton;
}

QObject *MessagesManager::qmlInstance(QQmlEngine *engine, QJSEngine *jsEngine)
{
    Q_UNUSED(engine);
    Q_UNUSED(jsEngine);

    return &instance();
}

int MessagesManager::nextMessageId()
{
    return ++NEXT_MESSAGE_ID;
}

/**
 * @brief 从数据库检查当前消息最大的ID，在以后创建本地消息ID时作为依据。
 */
void MessagesManager::loadDataFromDb()
{
    QSqlQuery query = DbManager::instance().createQuery(READ_MAX_MESSAGE_ID);
    query.exec();
    query.next();

    NEXT_MESSAGE_ID = query.value(0).toInt();
}

MessagesManager *MessagesManager::createInstance()
{
    MessagesManager* inst = new MessagesManager;
    return inst;
}

X_END_NAMESPACE
